package org.progin.cloudfolder.msg;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.progin.cloudfolder.Util;

public class SavePayload implements Payload {

	public String filename;
	private SavePayloadAdapter _adapter;
	
	public SavePayload(SavePayloadAdapter adapter) {
		_adapter = adapter;
	}
	
	@Override
	public byte getId() {
		return Payload.SAVE;
	}

	@Override
	public void write(DataOutputStream os) throws IOException {
		os.writeUTF(filename);
		_adapter.initWrite(filename);

		os.writeLong(_adapter.getFile().length());
		FileInputStream fis = null;

		while(true) {
			try{
				fis = new FileInputStream(_adapter.getFile());
				break;
			} catch(IOException ex) {
				System.out.println("SavePayload Write creating stream error... retrying");
				try {
					Thread.sleep(3000);
				} catch (InterruptedException ex1) {
					Logger.getLogger(SavePayload.class.getName()).log(Level.SEVERE, null, ex1);
				}
			}
		}
		
		Util.StreamCopyer(fis, os);
		fis.close();
	}

	@Override
	public void read(DataInputStream is) throws IOException {
		filename = is.readUTF();
		long len = is.readLong();

		_adapter.initRead(filename);
		FileOutputStream fos = null;

		while(true) {
			try{
				fos = new FileOutputStream(_adapter.getFile());
				break;
			} catch(IOException ex) {
				System.out.println("SavePayload Read creating stream error... retrying");
				try {
					Thread.sleep(3000);
				} catch (InterruptedException ex1) {
					Logger.getLogger(SavePayload.class.getName()).log(Level.SEVERE, null, ex1);
				}
			}
		}
		
		Util.StreamCopyer(is, fos, len);
		fos.flush();
		fos.close();
	}

}
